<template>
    <el-dialog v-model="visible" :title="title" @close="cancel" width="25%">
        <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px">
            <el-form-item label="友链名称" prop="name">
                <el-input v-model="dataForm.name"></el-input>
            </el-form-item>
            <el-form-item label="友链地址" prop="url">
                <el-input v-model="dataForm.url"></el-input>
            </el-form-item>
            <el-form-item label="友链类型" prop="linkFlag">
                <ma-dict-select v-model="dataForm.linkFlag" dict-type="link_type" style="width: 100%"></ma-dict-select>
            </el-form-item>
            <el-form-item label="图片" prop="imageUrl">
                <el-upload v-loading.fullscreen.lock="fullscreenLoading" class="avatar-uploader" :action="uploadApi2" :headers="uploadHeaders" :show-file-list="false" :before-upload="beforeUpload" :on-success="(res) => handleSuccess(res, index)">
                    <img v-if="dataForm.imageUrl" :src="dataForm.imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="启用状态" prop="status">
                <el-switch v-model="dataForm.status" inline-prompt :active-value="1" :inactive-value="0" active-text="启动" inactive-text="禁用" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
                <el-input-number v-model="dataForm.sort" :min="0" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="cancel()">取消</el-button>
            <el-button type="primary" @click="submit()">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { addLink, editLink } from '@/api/allApi'

const emit = defineEmits(['resetList'])

const visible = ref(false)
const title = ref('新增')
const dialogType = ref('add')
const dataFormRef = ref()
const dataForm = reactive({
	name: '',
	url: '',
	linkFlag: '',
	imageUrl: '',
	status: 0,
	sort: ''
})
const dataRules = reactive({})
const rowDate = reactive({})

const init = (type: string, row: any) => {
	visible.value = true
	dialogType.value = type
	Object.assign(rowDate, row) //浅拷贝，将row赋值给rowDate，用以前直接=赋值的形式会报错
	switch (type) {
		case 'add':
			title.value = '新增'
			break
		case 'edit':
			title.value = '修改'
			//回显
			for (let key in dataForm) {
				dataForm[key] = row[key]
			}
			break
		default:
			break
	}
}
import cache from '@/utils/cache' //为了获取token
const uploadApi2 = ref(import.meta.env.VITE_API_URL + '/sys/file/upload?access_token=' + localStorage.getItem('maToken')) //上传图片接口
const uploadHeaders = reactive({
	Accept: 'application/json, text/plain, */*',
	Authorization: cache.getToken()
}) //上传图片请求头
const fullscreenLoading = ref(false) //上传图片loading
const beforeUpload = (file: File) => {
	fullscreenLoading.value = true
}
//文件上传成功回调
const handleSuccess = (res: any, index: number) => {
	dataForm.imageUrl = res.data.url
	fullscreenLoading.value = false
}
const submit = () => {
	let api = addLink
	let obj = {
		...dataForm,
		tenantId: JSON.parse(localStorage.getItem('userInfo')).id, //租户id
		websiteId: Number(localStorage.getItem('WebsiteId')) //网站id
	}

	switch (dialogType.value) {
		case 'add':
			api = addLink
			obj.creator = JSON.parse(localStorage.getItem('userInfo')).id
			break
		case 'edit':
			api = editLink
			obj.updater = JSON.parse(localStorage.getItem('userInfo')).id
			obj.id = rowDate.id
			break
		default:
			break
	}
	api(obj).then((res: any) => {
		if (res.code === 0) {
			ElMessage.success('操作成功')
			emit('resetList')
			cancel()
		} else {
		}
	})
}
const cancel = () => {
	visible.value = false
	dataFormRef.value.resetFields()
}

defineExpose({
	init
})
</script>
<style lang="scss" scoped>
::v-deep(.avatar-uploader .el-upload) {
	border: 2px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
::v-deep(.avatar-uploader .el-upload:hover) {
	border-color: #409eff;
}
::v-deep(.avatar-uploader-icon) {
	font-size: 28px;
	color: #8c939d;
	width: 150px;
	height: 150px;
	line-height: 150px;
	text-align: center;
}
::v-deep(.avatar) {
	width: 150px;
	height: 150px;
	display: block;
}
</style>
